
//+build darwin linux

package shell_util

import (
	"gitee.com/lwow2025/snake-go/common/util"
	"path/filepath"
	"os"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"os/exec"
	"fmt"
	"gitee.com/lwow2025/snake-go/common/log"
	"bufio"
	"bytes"
	"strings"
)

func ExecCmdByTmpFile(cmd []byte, shFileArgs ...string) (rb []byte, err error) {
	tmpPath := filepath.Join(util.HomeDir(), "tmp")
	os.MkdirAll(tmpPath, 0755)

	tmpShFile := filepath.Join(tmpPath, bson.NewObjectId().Hex() + ".sh")
	ioutil.WriteFile(tmpShFile, cmd, 0755)
	defer os.RemoveAll(tmpShFile)

	args := append([]string{ tmpShFile }, shFileArgs...)
	//log.L.Sugar().Debug(string(cmd), " ", args)
	rb, err = exec.Command("/bin/bash", args...).Output()
	return
}

func Alive(appStartCmd string) bool {
	rb, err := ExecCmdByTmpFile([]byte(fmt.Sprintf(`ps aux|grep "%v"`, appStartCmd)))
	if err != nil {
		log.L.Sugar().Error("check app alive failed", " result=", string(rb), " err=", err)
		return false
	}

	counter := 0
	scanner := bufio.NewScanner(bytes.NewReader(rb))
	for scanner.Scan() {
		tmpText := scanner.Text()
		if strings.Contains(tmpText, appStartCmd) {
			counter++
		}
	}

	if counter > 1 {
		return true
	}
	return false
}
